<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="">
        <el-breadcrumb-item
          ><div class="div1">商品管理</div></el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/giftList' }"
          ><div class="div3">赠品列表</div></el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><div class="div2">赠品详情</div></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <!-- 面包屑导航 -->
    <div class="baisc">
      <p class="header">基本信息</p>
      <el-form :model="baisc" class="demo-form-inline">
        <div class="nav">
          <el-form-item label="赠品主图">
            <el-upload
              class="upload-demo"
              list-type="picture"
              action="#"
              :show-file-list="false"
              :http-request="safeImport"
              v-model="imageUrl"
            >
              <!-- 		  :file-list="fileList"
													:limit='1' -->
              <el-button slot="trigger" size="small" type="primary"
                >点击上传</el-button
              >
            </el-upload>

            <div class="notes">
              <!-- v-for='(item,index) in fileList' :key='index' -->
              <p>
                <img
                  v-if="!is_null(imageUrl)"
                  v-image-preview
                  :src="ImgHttps + imageUrl"
                  class="avatar"
                />
                <span v-if="!is_null(imageUrl)" @click="close(index)">×</span>
              </p>
            </div>
          </el-form-item>
          <div class="stock">
            <el-form-item label="赠品标题" label-width="70px">
              <el-input
              maxlength="32"
                v-model="baisc.title"
                placeholder="请输入赠品标题"
              ></el-input>
            </el-form-item>

            <el-form-item label="赠品编号" label-width="70px">
              <el-input
              :controls="false"
                v-model="baisc.nort"
                placeholder="请输入赠品编号"
              ></el-input>
            </el-form-item>
          </div>

          <div class="stock">
            <el-form-item label="选择品牌">
              <el-select
                v-model="baisc.brand"
                placeholder="请选择产品品牌"
                filterable
                clearable
              >
                <el-option
                  v-for="items in brandselect"
                  :key="items.id"
                  :label="items.name"
                  :value="items.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="品牌分类">
              <el-cascader
                v-model="baisc.category"
                :options="options"
                :props="{
                  checkStrictly: true,
                  label: 'name',
                  value: 'id',
                  children: 'children',
                }"
                filterable
                clearable
              ></el-cascader>
            </el-form-item>
          </div>
        </div>

        <div class="guige">
          <p class="header">规格价格</p>
          <div class="standards">
            <el-form-item label-position="right" label="赠品规格">
              <el-radio-group
                v-model="baisc.resource"
                v-for="items in commDictonary"
                :key="items.id"
                style="margin-right: 10px"
              >
                <el-radio :label="items.id">{{ items.name }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="stock">
              <el-form-item label="赠品重量" label-width="70px">
                <el-input
                  v-model="baisc.weight"
                  placeholder="请输入赠品重量"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="赠品数量"
                label-width="70px"
                v-if="baisc.resource == '件'"
              >
                <el-input
                  v-model="baisc.number"
                  placeholder="请输入赠品一件的总量"
                ></el-input>
              </el-form-item>
            </div>
            <el-form-item label="赠品价格" label-width="70px">
              <div class="price">
                <el-input
                  v-model="baisc.newPrice"
                  placeholder="优惠价"
                ></el-input>
                <span>元</span>
                <el-input
                  v-model="baisc.oldPrice"
                  placeholder="市场价"
                ></el-input>
                <span>元</span>
              </div>
            </el-form-item>

            <div class="stock1">
              <el-form-item label="赠品仓库" width="100px">
                <el-select
                  v-model="houseName"
                  placeholder="请选择赠品类别"
                  value-key="id"
                  multiple
                  @change="stockE"
                >
                  <el-option
                    v-for="items in house"
                    :key="items.id"
                    :value="items"
                    :label="items.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>

            <div class="wareHouse">
              <span v-for="(items, index) in houseName" :key="index">
                <el-form-item :label="items.name">
                  <el-input
                    disabled
                    v-model="items.value"
                    type="Number"
                    placeholder="请输入商品库存"
                  ></el-input>
                </el-form-item>
              </span>
            </div>
            <el-form-item label="赠品库存" label-width="70px">
              <el-input
                :value="totalCount"
                disabled
                placeholder="请输入赠品库存"
              ></el-input>
              <!-- <span>{{baisc.resource}}</span> -->
            </el-form-item>
            <el-form-item label="赠品介绍">
              <el-input type="textarea" v-model="baisc.desc"></el-input>
            </el-form-item>

            <el-form-item label="是否上架" style="width: 150px">
              <el-switch
                v-model="baisc.status"
                :active-value="0"
                :inactive-value="1"
              ></el-switch>
            </el-form-item>
          </div>
          <div class="jurisdictionBox">
            <!-- <p class="header">销售权限</p> -->
            <div class="jurisdiction">
              <el-form-item label="可以销售">
                <el-checkbox-group v-model="checkedCities"  @change="checkboxChange">
                  <el-checkbox
                    v-for="city in selectList"
                    :key="city.dictId"
                    :label="city.dictId"
                    >{{ city.dictName }}</el-checkbox
                  >
                </el-checkbox-group>

                <!-- 推广部（内部，总部） -->
                <div class="inter" style="margin-left: 90px" v-if="enterIf">
                  <el-radio v-model="tgInter" label="1">内部</el-radio>
                  <el-radio v-model="tgInter" label="2">总部</el-radio>
                </div>
                <!-- 推广部（内部，总部） -->

              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="tolist">保存</el-button>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      baisc: {
        title: "",
        brand: "",
        resource: "", //规格
        weight: "",
        newPrice: "",
        oldPrice: "",
        desc: "",
        stock: "", //库存
        category: [],
        wareHouse: "", //仓库
        status: 0,
        nort: "",
      },
      imageUrl: "",
      selectList: [],
      options: [],
      houseName: [],
      brandselect: [],
      house: "", //仓库
      commDictonary: "", //规格数据接受
      fileList: [],
      id: "",
      checkedCities: [],
      tgInter: "",
      enterIf: false,
    };
  },
  created() {
    this.brandSelect();
    this.brandSelectBox();
  },
  activated() {
    if (
      this.$route.query.id &&
      this.id != this.$route.query.id &&
      this.$route.query.type != 0
    ) {
      this.brandSelect();
      this.brandSelectBox();
      this.id = this.$route.query.id;
      if (this.id == "" || this.id == undefined) {
        // console.log('详情判断')
      } else {
        this.todetail();
      }
    }

    if (this.$route.query.type === 0) {
      this.brandSelect();
      this.brandSelectBox();
      this.baisc = {
        title: "",
        brand: "",
        resource: "", //规格
        weight: "",
        newPrice: "",
        oldPrice: "",
        desc: "",
        stock: "", //库存
        cj: "",
        number: "",
        category: [],
        wareHouse: "", //仓库
        status: 0, //0上级
        gift: 0, //无赠品
        nort: "",
      };
      this.imageUrl = "";
      this.checkedCities = [];
    }
  },
  methods: {
    checkboxChange(e) {
      if (e.indexOf("1") != -1) {
        this.enterIf = true;
      } else {
        this.enterIf = false;
      }
    },
    // 赠品详情
    // 获取详情信息
    todetail() {
      if (this.id == undefined || this.id == "") {
        // console.log(this.id)
      } else {
        this.axios
          .get(
            "/order/comm/complimentary/selectComplimentaryById?id=" + this.id
          )
          .then((res) => {
            // console.log('获取详情信息')
            // console.log(res)

            if (res.code == 0) {
              let hn = res.data.complimentary.warehouses;
              this.houseName = res.data.warehouses ? res.data.warehouses : [];
              if (hn) {
                for (let item of hn) {
                  item.id = Number(item.warId);
                  item.value = item.number;
                  item.name = item.warName;
                }
                this.houseName = hn;
              } else {
                this.houseName = [];
              }
              this.baisc = {
                title: res.data.complimentary.title,
                brand: res.data.complimentary.brandId,
                resource: res.data.complimentary.specificationId, //规格
                weight: res.data.complimentary.weight,
                newPrice: res.data.complimentary.sellPrice,
                oldPrice: res.data.complimentary.marketPrice,
                desc: res.data.complimentary.comment,
                stock: res.data.complimentary.quantityStock, //库存
                cj: res.data.complimentary.vender,
                category: res.data.complimentary.categoryId,
                wareHouse: res.data.complimentary.warehouses, //仓库
                status: res.data.complimentary.status,
                nort: res.data.complimentary.code,
                tgInter: res.data.complimentary.depa,
              };
              this.imageUrl = res.data.complimentary.image;
              let obj = {
                img: this.ImgHttps + res.data.complimentary.image,
              };
              this.fileList.push(obj);
              this.checkedCities = [];
              for (let i = 0; i < res.data.commPermissionsList.length; i++) {
                //销售权限
                this.checkedCities.push(
                  res.data.commPermissionsList[i].dictId.toString()
                );
              }
            } //code
            if (this.checkedCities.indexOf("1") != -1) {
              this.enterIf = true;
            } else {
              this.enterIf = false;
            }
          });
      }
    },
    // 保存数据 start
    tolist() {
      // if (this.houseName) {
      //   for (let i of this.houseName) {
      //     if (!i.value) {
      //       this.$message.error("请输入仓库数量");
      //       return;
      //     }
      //   }
      // }
      let that = this;
      if (this.id == "" || this.id == undefined) {
        // if (that.imageUrl == "") {
        //   that.$message.error("赠品图片不能为空");
        // } else
        // else if (!that.totalCount) {
        //   that.$message.error("赠品库存不能为空");
        // } else if (!that.totalCount) {
        //   that.$message.error("赠品仓库不能为空1");
        // }
        if (that.baisc.title == "") {
          that.$message.error("赠品名字不能为空");
        } else if (that.baisc.brand == "") {
          that.$message.error("赠品品牌不能为空");
        } else if (that.baisc.category == "") {
          that.$message.error("赠品分类不能为空");
        } else if (that.baisc.resource == "") {
          that.$message.error("赠品规格不能为空");
        } else if (that.baisc.newPrice == "") {
          that.$message.error("赠品价格不能为空");
        } else if (that.baisc.oldPrice == "") {
          that.$message.error("赠品市场价不能为空");
        } else {
          //*** 循环销售权限 ***//
          let commPermissionsList = [];
          for (let i = 0; i < that.checkedCities.length; i++) {
            let obj = { dictId: that.checkedCities[i] };
            commPermissionsList.push(obj);
          }
          //*** 循环销售权限 ***//
          that.axios
            .post("/order/comm/complimentary/addComplimentary", {
              brandId: that.baisc.brand,
              commPermissionsList: commPermissionsList,
              categoryId: that.baisc.category[that.baisc.category.length - 1], //赠品类别
              comment: that.baisc.desc,
              complimentaryId: "", //	赠品id
              createdBy: sessionStorage.getItem("user_id"),
              entrepotId: that.baisc.wareHouse, //赠品仓库
              image: that.imageUrl,
              isComplimentary: "", //是否有赠品
              marketPrice: that.baisc.oldPrice, //赠品市场价
              quantityStock: parseInt(that.baisc.stock), //赠品库存数量
              sellPrice: that.baisc.newPrice, //赠品现卖价
              specificationId: that.baisc.resource, //赠品规格
              status:that.baisc.status, //赠品上架状态
              title: that.baisc.title,
              weight: that.baisc.weight, //赠品重量
              code: that.baisc.nort,
              depa: that.tgInter,
            })
            .then((res) => {
              // console.log(res);
              if (res.code == 0) {
                this.$message.success("添加成功");
                that.$router.push("/giftList");
              } else {
                this.$message.error(res.message);
              }
            });
        }
      } else {
        //修改赠品信息
        // if (that.imageUrl == "") {
        //   that.$message.error("赠品图片不能为空");
        // } else
        // else if (!that.totalCount) {
        //   that.$message.error("赠品库存不能为空");
        // } else if (!that.totalCount) {
        //   that.$message.error("赠品仓库不能为空1");
        // }

        if (that.baisc.title == "") {
          that.$message.error("赠品名字不能为空");
        } else if (that.baisc.brand == "") {
          that.$message.error("赠品品牌不能为空");
        } else if (that.baisc.category == "") {
          that.$message.error("赠品分类不能为空");
        } else if (that.baisc.resource == "") {
          that.$message.error("赠品规格不能为空");
        } else if (that.baisc.newPrice == "") {
          that.$message.error("赠品价格不能为空");
        } else if (that.baisc.oldPrice == "") {
          that.$message.error("赠品市场价不能为空");
        } else if(that.baisc.nort == undefined){
          that.$message.warning("赠品编号不能为空");
        } else {
          let commPermissionsList = [];
          for (let i = 0; i < that.checkedCities.length; i++) {
            let obj = { dictId: that.checkedCities[i] };
            commPermissionsList.push(obj);
          }
          let newTemp = [];
          if (this.houseName) {
            for (let item of this.houseName) {
              newTemp.push({
                warId: item.id,
                quantityStock: Number(item.value),
              });
            }
          }
          that.axios
            .post("/order/comm/complimentary/updateComplimentary", {
              brandId: that.baisc.brand,
              commPermissionsList: commPermissionsList,
              categoryId: that.baisc.category[that.baisc.category.length - 1], //赠品类别
              comment: that.baisc.desc,
              complimentaryId: "", //	赠品id
              updatedBy: sessionStorage.getItem("user_id"),
              warehouseComs: newTemp, //赠品仓库
              image: that.imageUrl,
              isComplimentary: "", //是否有赠品
              marketPrice: that.baisc.oldPrice, //赠品市场价
              quantityStock: parseInt(that.baisc.stock), //赠品库存数量
              sellPrice: that.baisc.newPrice, //赠品现卖价
              specificationId: that.baisc.resource, //赠品规格
              status:that.baisc.status, //赠品上架状态
              title: that.baisc.title,
              weight: that.baisc.weight, //赠品重量
              id: this.id,
              code: that.baisc.nort != undefined?that.baisc.nort:"",
              depa: that.tgInter,
            })
            .then((res) => {
              // console.log(res);
              if (res.code == 0) {
                this.$message.success("编辑成功");
                that.$router.push("/giftList");
              } else {
                this.$message.error(res.message);
              }
            });
        }
        // }
      }
    },
    stockE(e) {
      this.houseName = e;
    },
    //** 品牌下拉 **//
    brandSelectBox() {
      this.axios
        .get("/order/comm/commodity/selectList", {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          // console.log('分类')
          // console.log(res);
          if (res.code == 0) {
            this.brandselect = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
      // 查询仓库 //
      this.axios
        .get("/order/comm/commodity/selectCommWarehouse", {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          // console.log('查询仓库')
          // console.log(res);
          if (res.code == 0) {
            this.house = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
      //赠品规格//
      this.axios
        .get("/order/comm/commDictonary/list", {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          // console.log('赠品规格')
          // console.log(res);
          if (res.code == 0) {
            this.commDictonary = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    //** 品牌下拉 **//
    // 分类下拉框
    brandSelect() {
      this.axios
        .get("/order/comm/commodity/selectBrand", {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          // console.log('分类')
          // console.log(res);
          if (res.code == 0) {
            this.options = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
      // 销售权限
      this.axios
        .get("/sys/v1/common/by/group?groupId=sales_authority", {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          // console.log(res);
          if (res.code == 0) {
            this.selectList = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 分类下拉框
    // 图片上传
    safeImport(fileObj) {
      let formData = new FormData();
      formData.append("file", fileObj.file);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      this.axios
        .post(
          "/sys/v1/common/upload/files?pathName=internalSystem",
          formData,
          config
        )
        .then((res) => {
          // console.log(res);
          if (res.code == 0) {
            this.imageUrl = res.data.url;
            // let obj={
            // 	img:this.ImgHttps+res.data.url
            // }
            // this.fileList.push(obj);
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 删除图片
    close(index) {
      this.fileList.splice(index, 1);
      this.imageUrl = "";
    },
    // 图片预览
    prodCode() {
      this.axios
        .get("/order/comm/commodity/generate/prodCode", {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          // console.log(res)
          if (res.code == 0) {
            this.baisc.nort = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    is_null(content) {
      if (content) {
        return false;
      } else {
        return true;
      }
    },
  },
  computed: {
    totalCount() {
      if (this.houseName.length) {
        let count = 0;
        for (let item of this.houseName) {
          count += !item.value ? 0 : Number(item.value);
        }
        return count;
      }
      return 0;
    },
  },
};
</script>

<style scoped lang="scss">
.div1 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb2.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}

.div2 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb1.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #fff;
}
.div3 {
  margin-left: -8px;
  background: url(../../../assets/breadcrumb3.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
.header {
  font-size: 16px;
  color: #2d7edf;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.baisc {
  background: #fff;
  padding: 10px;
  /deep/.el-input__inner {
    width: 200px;
  }
}
.nav,
.standards {
  margin-left: 100px;
  margin-top: 20px;
}
.selectBox {
  /deep/.el-input {
    display: inline-block;
  }

  /deep/.el-form-item {
    margin-top: 20px;
    display: inline-block;
    width: 300px;
  }
}
/deep/.el-input__inner {
  height: 35px;
  line-height: 35px;
}
.avatar-uploader .el-upload {
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px solid #eee;
}
.demo-form-inline {
  margin-top: 20px;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.price {
  /deep/.el-input {
    display: inline-block;
    width: 200px;
  }
  span {
    color: #999;
    display: inline-block;
    margin: 0 30px 0 10px;
  }
}
.stock {
  .el-form-item {
    display: inline-block;
    width: 330px;
  }
  /deep/.el-input {
    display: inline-block;
    width: 200px;
  }
  span {
    font-size: 15px;
    color: #999;
    display: inline-block;
    margin-left: 10px;
  }
}
.wareHouse {
  /deep/.el-input {
    width: 150px;
  }
  .el-form-item {
    display: inline-block;
    width: 200px;
  }
  /deep/.el-form-item__content {
    width: 200px;
  }
  /deep/.el-input__inner {
    width: 150px;
    display: inline-block;
  }
}
.stock1 {
  .el-form-item {
    display: inline-block;
    width: 500px;
  }
  /deep/.el-input__inner {
    width: 400px;
  }
  /deep/.el-input {
    display: inline-block;
    width: 400px;
  }
  span {
    font-size: 15px;
    color: #999;
    display: inline-block;
    margin-left: 10px;
  }
}
/deep/.el-textarea {
  width: 600px;
}

.jurisdiction {
  margin-left: 100px;
  margin-top: 20px;
  /deep/.el-checkbox-group {
    display: inline-block;
    margin-left: 30px;
  }
  /deep/.el-button {
    padding: 8px 12px;
  }
}
.notes {
  margin-left: 70px;
  p {
    margin-top: 10px;
    display: inline-block;
    margin-right: 10px;
    position: relative;
    img {
      width: 150px;
      height: 150px;
    }
  }
  span {
    display: block;
    width: 18px;
    height: 18px;
    line-height: 20px;
    text-align: center;
    font-size: 13px;
    color: #fff;
    background: #409eff;
    position: absolute;
    top: -5px;
    right: -6px;
    border-radius: 50%;
  }
}
</style>
